package com.example.figurehecheng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.figurehecheng.common.config.checkObjAllFieldsIsNull;
import com.example.figurehecheng.common.constant.MessageConstant;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.common.exception.AccountExist;
import com.example.figurehecheng.domain.dto.CommentDTO;
import com.example.figurehecheng.domain.entity.Comment;
import com.example.figurehecheng.domain.entity.Merchant;
import com.example.figurehecheng.domain.entity.User;
import com.example.figurehecheng.domain.vo.CommentVO;
import com.example.figurehecheng.mapper.CommentMapper;
import com.example.figurehecheng.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.figurehecheng.service.IMerchantService;
import com.example.figurehecheng.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 宇科工作室
 * @since 2024-10-18
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {


    private final IUserService iUserService;

    private final IMerchantService iMerchantService;
    /**
     * 获取评论和打分
     *
     * @return
     */
    @Override
    public List getComment() {
        List<Comment> comments = lambdaQuery()
                .eq(Comment::getShopId, BaseContext.getCurrentId())
                .orderByDesc(Comment::getTime)
                .list();

        List<User> list = iUserService.list();
        CommentVO commentVO = null;
        Map<Object, Object> map = new HashMap<>();
        //设置回复名字
      List<CommentVO> commentVOS = new ArrayList<>();
        for (int i = 0; i < comments.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (ObjectUtil.equal(comments.get(i).getUserId(), list.get(j).getId()) && comments.get(i).getUserId() != null) {
                   commentVO = BeanUtil.copyProperties(comments.get(i), CommentVO.class);
                    commentVO.setName(list.get(j).getName());
                    commentVOS.add(commentVO);
                }
            }
            if (comments.get(i).getUserId() == null) {
                 commentVO = BeanUtil.copyProperties(comments.get(i), CommentVO.class);
                commentVO.setName("商家回复");
                commentVOS.add(commentVO);
            }
        }

         //获取平均分
        double sum = comments.stream().filter(item -> item.getMark() != null).map(Comment::getMark).reduce(Integer::sum).get();
        double size = comments.stream().filter(item -> item.getMark() != null).collect(Collectors.toList()).size();
        map.put("avg", BigDecimal.valueOf(sum / size));

        //算好评差评的占比
        double sums= comments.stream().filter(item -> item.getMark() != null&&item.getMark()<=2).map(Comment::getMark).reduce(Integer::sum).get();
        BigDecimal bigDecimalSums = BigDecimal.valueOf(sums);
        BigDecimal bigDecimalSum = BigDecimal.valueOf(sum);
        BigDecimal result = bigDecimalSums.divide(bigDecimalSum, 2, RoundingMode.HALF_UP);
        map.put("sums",result);

        //查询一二级评论分类
        List<CommentVO> collectPid = commentVOS.stream().filter(item -> item.getPid() == null).collect(Collectors.toList());
        for (CommentVO commentVOs : collectPid) {
            List<CommentVO> collect = commentVOS.stream().filter(item -> item.getPid() != null&&commentVOs.getId().equals(item.getPid())).collect(Collectors.toList());
            commentVOs.setChildren(collect);
        }
        map.put("comment",collectPid);
        //将map转会list
        ArrayList<Object> avgComment = new ArrayList<>(map.values());
        return avgComment;
    }

    /**
     * 商家回复评论
     */
    @Override
    public void sureComment(CommentDTO commentDTO) {
        if (ObjectUtil.isEmpty(commentDTO.getContent())){
            throw new AccountExist(MessageConstant.COMMENT_ERROR);
        }
        Merchant merchant = iMerchantService.getOne(new QueryWrapper<Merchant>().lambda().eq(Merchant::getId, BaseContext.getCurrentId()));
        Comment comment = BeanUtil.copyProperties(commentDTO, Comment.class);
        comment.setTime(LocalDateTime.now().toString());
        comment.setShopId(BaseContext.getCurrentId().intValue());
        comment.setType(merchant.getRole());
        save(comment);
    }
}
